<template>
  <div class="car-select">
    <van-nav-bar
      title="选择车型"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />

    <!-- 搜索栏 -->
    <van-search
      v-model="searchValue"
      placeholder="搜索车型/品牌"
      @search="onSearch"
      shape="round"
      show-action
      @cancel="onCancel"
    />

    <van-row>
      <van-col span="24">
        <van-dropdown-menu>
          <van-dropdown-item v-model="filters.type" :options="typeOptions" />
          <van-dropdown-item v-model="filters.level" :options="levelOptions" />
          <van-dropdown-item
            v-model="filters.powerType"
            :options="powerTypeOptions"
          />
          <van-dropdown-item title="更多筛选" @click="showFilter = true" />
        </van-dropdown-menu>
      </van-col>
    </van-row>

    <!-- 车辆列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div class="car-list">
          <van-card
            v-for="car in cars"
            :key="car.id"
            :price="car.dailyRate"
            :title="car.brand + ' ' + car.model"
            :thumb="car.coverImage"
            :price-description="'/天'"
            class="car-card"
          >
            <template #thumb>
              <div class="car-image">
                <img :src="car.coverImage" :alt="car.model" />
              </div>
            </template>

            <template #tags>
              <div class="car-tags">
                <van-tag plain type="danger" style="margin-right: 4px">{{
                  car.type
                }}</van-tag>
                <van-tag plain type="primary"
                  >{{ car.specifications.seats }}座</van-tag
                >
                <van-tag plain type="warning" style="margin-left: 4px">{{
                  car.level
                }}</van-tag>
              </div>
            </template>

            <template #desc>
              <div class="car-desc">
                <p class="specs">
                  <span>{{ car.specifications.powerType }}</span>
                  <span class="dot">·</span>
                  <span>{{ car.specifications.trunkCapacity }}L后备箱</span>
                  <span class="dot">·</span>
                  <span>{{ car.specifications.fuelConsumption }}L/100km</span>
                </p>
                <p class="location">取车地：{{ car.city }}</p>
                <p class="return-cities" v-if="car.returnCities?.length">
                  可还车城市：{{ car.returnCities.join("、") }}
                </p>
              </div>
            </template>

            <template #price-top>
              <div class="rating" v-if="car.rentalHistory.rentCount > 0">
                <van-rate
                  :value="car.rentalHistory.averageRating"
                  :size="12"
                  color="#ffd21e"
                  void-icon="star"
                  void-color="#eee"
                  readonly
                />
                <span class="rent-count"
                  >已租{{ car.rentalHistory.rentCount }}次</span
                >
              </div>
            </template>

            <template #footer>
              <van-button
                size="small"
                type="primary"
                @click="selectThisCar(car)"
                class="rent-button"
              >
                立即预订
              </van-button>
            </template>
          </van-card>
        </div>
      </van-list>
    </van-pull-refresh>

    <!-- 更多筛选弹出层 -->
    <van-popup
      v-model:show="showFilter"
      position="right"
      style="width: 85%; height: 100%"
    >
      <div class="filter-popup">
        <van-nav-bar
          title="筛选条件"
          left-text="取消"
          right-text="确定"
          @click-left="onFilterCancel"
          @click-right="onFilterConfirm"
        />

        <div class="filter-content">
          <van-cell-group title="价格区间">
            <van-field
              v-model="filters.minPrice"
              type="number"
              label="最低价"
              placeholder="请输入"
            />
            <van-field
              v-model="filters.maxPrice"
              type="number"
              label="最高价"
              placeholder="请输入"
            />
          </van-cell-group>

          <van-cell-group title="座位数">
            <van-radio-group v-model="filters.seats">
              <van-cell-group inset>
                <van-cell title="5座" clickable @click="filters.seats = 5">
                  <template #right-icon>
                    <van-radio :name="5" />
                  </template>
                </van-cell>
                <van-cell title="7座" clickable @click="filters.seats = 7">
                  <template #right-icon>
                    <van-radio :name="7" />
                  </template>
                </van-cell>
              </van-cell-group>
            </van-radio-group>
          </van-cell-group>

          <van-cell-group title="还车城市">
            <van-field
              v-model="filters.returnCity"
              is-link
              readonly
              label="还车城市"
              placeholder="请选择"
              @click="showCityPicker = true"
            />
          </van-cell-group>
        </div>
      </div>
    </van-popup>

    <!-- 城市选择弹出层 -->
    <van-popup v-model:show="showCityPicker" position="bottom">
      <van-picker
        show-toolbar
        title="选择还车城市"
        :columns="cityOptions"
        @confirm="onCitySelect"
        @cancel="showCityPicker = false"
        :default-index="0"
        swipe-duration="500"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { showToast } from "vant";
import { useRentalStore } from "@/stores/rental";
import { getCars } from "@/api/car";
import { getCarReviews } from "@/api/review";

const router = useRouter();
const route = useRoute();
const rentalStore = useRentalStore();

// 搜索相关
const searchValue = ref("");
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const page = ref(1);
const limit = 10;
const cars = ref([]);

// 筛选相关
const filters = reactive({
  type: "",
  level: "",
  powerType: "",
  minPrice: "",
  maxPrice: "",
  seats: "",
  returnCity: "",
  brand: "",
  model: "",
  city: route.query.city,
});

const typeOptions = [
  { text: "全部车型", value: "" },
  { text: "经济型", value: "economy" },
  { text: "舒适型", value: "comfort" },
  { text: "豪华型", value: "luxury" },
];

const levelOptions = [
  { text: "全部级别", value: "" },
  { text: "A级", value: "A" },
  { text: "B级", value: "B" },
  { text: "C级", value: "C" },
];

const powerTypeOptions = [
  { text: "全部动力", value: "" },
  { text: "汽油", value: "gasoline" },
  { text: "新能源", value: "electric" },
  { text: "混动", value: "hybrid" },
];

// 获取车辆列表
const fetchCars = async (params = {}) => {
  console.log("fetchCars 被调用，参数:", params); // 添加日志
  try {
    loading.value = true;
    const searchParams = {
      city: params.city,
      status: params.status,
      page: params.page,
      limit: params.limit,
    };

    console.log("发送API请求，参数:", searchParams); // 添加日志
    const data = await getCars(searchParams);

    if (refreshing.value) {
      cars.value = data.cars;
      refreshing.value = false;
    } else {
      cars.value = [...cars.value, ...data.cars];
    }

    finished.value = cars.value.length >= data.pagination.total;
  } catch (error) {
    showToast(error.message || "获取车辆列表失败");
  } finally {
    loading.value = false;
  }
};

// 获取车辆评价
const fetchCarReviews = async (carId) => {
  try {
    const reviews = await getCarReviews(carId);
    return reviews;
  } catch (error) {
    console.error("获取评价失败:", error);
    return [];
  }
};

// 下拉刷新
const onRefresh = () => {
  finished.value = false;
  page.value = 1;
  fetchCars();
};

// 上拉加载
const onLoad = () => {
  if (!loading.value) {
    page.value += 1;
    const loadMoreParams = {
      city: rentalStore.pickupCity,
      pickupDate: rentalStore.pickupDate,
      returnDate: rentalStore.returnDate,
      page: page.value,
      limit: 10,
    };
    fetchCars(loadMoreParams);
  }
};

// 搜索
const onSearch = () => {
  page.value = 1;
  finished.value = false;
  const searchParams = {
    city: rentalStore.pickupCity,
    pickupDate: rentalStore.pickupDate,
    returnDate: rentalStore.returnDate,
    page: page.value,
    limit: 10,
  };
  fetchCars(searchParams);
};

const onCancel = () => {
  searchValue.value = "";
  onSearch();
};

// 筛选相关
const showFilter = ref(false);
const showCityPicker = ref(false);

const onFilterConfirm = () => {
  rentalStore.setFilters(filters);
  showFilter.value = false;
  page.value = 1;
  finished.value = false;
  fetchCars();
};

const onFilterCancel = () => {
  showFilter.value = false;
};

// 城市选择器数据
const cityOptions = ["赣州", "南昌", "深圳", "广州", "北京", "上海"];

// 城市选择确认
const onCitySelect = (value) => {
  filters.returnCity = value;
  showCityPicker.value = false;
};

// 选择车辆
const selectThisCar = (car) => {
  router.push({
    path: `/car-detail/${car._id}`,
    query: {
      pickupDate: route.query.pickupDate,
      returnDate: route.query.returnDate,
      city: route.query.city,
      returnCity: filters.returnCity,
    },
  });
};

// 返回处理
const onClickLeft = () => {
  router.back();
};

onMounted(() => {
  // 从路由参数初始化信息
  const { city } = route.query;
  console.log("路由参数:", city); // 添加日志

  // 如果没有必要的参数，返回首页
  if (!city) {
    showToast("请先选择取车城市");
    router.replace("/");
    return;
  }

  // 将租车时间信息存储到 store 中，供后续创建订单使用
  if (route.query.pickupDate && route.query.returnDate) {
    rentalStore.setDates(route.query.pickupDate, route.query.returnDate);
  }
  rentalStore.setCities(city);

  // 设置初始筛选参数，只使用城市和状态
  const initialParams = {
    city: city,
    page: 1,
    limit: 10,
    status: "可租",
  };

  console.log("发起搜索，参数:", initialParams); // 添加日志
  // 立即进行搜索
  fetchCars(initialParams);
});
</script>

<style scoped lang="scss">
.car-select {
  min-height: 100vh;
  background: #f7f8fa;
}

.car-list {
  padding: 12px;

  .car-card {
    margin-bottom: 12px;
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

    .car-image {
      width: 100%;
      height: 120px;
      overflow: hidden;
      border-radius: 4px;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    :deep(.van-card__header) {
      padding-top: 8px;
    }

    :deep(.van-card__title) {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }

    .car-tags {
      margin: 8px 0;
    }

    .car-desc {
      font-size: 12px;
      color: #666;
      line-height: 1.6;

      .specs {
        display: flex;
        align-items: center;

        .dot {
          margin: 0 4px;
          color: #999;
        }
      }

      .location,
      .return-cities {
        margin-top: 4px;
        color: #999;
      }
    }

    .rating {
      display: flex;
      align-items: center;
      margin-bottom: 4px;

      .rent-count {
        margin-left: 4px;
        font-size: 12px;
        color: #999;
      }
    }

    :deep(.van-card__price) {
      color: #ff6b6b;
      font-weight: bold;
      font-size: 18px;
    }

    :deep(.van-card__price-description) {
      color: #999;
    }

    .rent-button {
      border-radius: 4px;
      font-weight: normal;
    }
  }
}

// 适配暗色模式
@media (prefers-color-scheme: dark) {
  .car-card {
    background: #1c1c1e !important;

    :deep(.van-card__title) {
      color: #fff !important;
    }

    .car-desc {
      color: #999 !important;
    }
  }
}

.filter-popup {
  display: flex;
  flex-direction: column;
  height: 100%;

  .filter-content {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
  }
}
</style> 